{% extends "../base.html" %}
{% block content %}

  <script language="javascript" type="text/javascript"> 
  
    function getLink(_p)
    {
      var html = '<a href="/trip?pid=' + _p +'">' + _p + '</a>';
      document.write(html);
    }
    
    function isTrip()
    {
      var oper = document.getElementById('fld_form').elements['oper'];
      return oper[0].checked;
    }

    function getDays()
    {
      var days = 0;
      if (isTrip())
      {
        for (var i=1; i<=2; i++) 
        {
          for (var j=1; j<=7; j++) 
          {
            if (document.getElementById('fld_form').elements['ndays' + i + j].checked)
              days += (1 << ((j-1)*2+i-1));
          }
        }
      }
      return days;
    }
    
    function myClick(_num)
    {
      var frm = document.getElementById('fld_form');
      var act = frm.elements['action'];
      switch (_num) {
        case 1:  act.value = 'insert'; break;
        case 2:  act.value = 'update'; break;
        case 3:  act.value = 'delete'; break;
        case 4:  act.value = 'cancel'; break;
        default: act.value = 'undef'; 
      }
    
      frm.elements['ret_days'].value = getDays();
      
      frm.Submit();
      return true;
    }
    
    function setOption(_num, _sel)
    {
      var html = '<option value="' + _num + '" ';
      if (_sel == _num)
        html += 'selected ';
      html += '>';
      document.write(html);
    }

    currentDays = 0;
    
    function makeWeek(_oper,_days)
    {
      if (_oper == 1)
      {
        document.getElementById('days_row').innerHTML = '';
        return;
      }

      currentDays = _days;

      var today = new Date().getDay();
      if (today == 0)
        today = 6;
      else
        today--;
      var days = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];

      var html = '<td class="fl1">Дни:</td><td class="fl2"><table>';
      for (var d=0; d<=6; d++)
      {
        html += '<th>';
        if (d != today)
          html += days[d];
        else
          html += '<span class="currentDayOfWeek">' + days[d] + '</span>';
        html += '</th>';
      }
      var shift = 0;
      for (var i=1; i<=2; i++) {
        html += '<tr>';
        for (var j=1; j<=7; j++) {
          var chk = '';
          if ((_days & (1 << ((j-1)*2+i-1))) != 0)
            chk = ' checked';
          html += '<td><input name="ndays' + i + j + '" type="checkbox"' + chk + ' onChange="check()" /></td>';
          shift++;
        }
        html += '</tr>';
      }
      html += '</table></td>';
      document.getElementById('days_row').innerHTML = html;
      return true;
    }
    
    function setRadio(_num, _sel, _name)
    {
      var html = '<input type="radio" name="oper" value="' + _num + '" ';
      if (_sel == _num)
        html += 'checked ';
      html += 'onChange="checkOper(' + _num + ', ' + currentDays + ')"/>' + _name;
      if (_num < 1)
        html += '<br />';
      document.write(html);
    }

    function getWeekPeriod()
    {
      var year = parseInt(document.getElementById('year').value);
      var week = parseInt(document.getElementById('week').value);
      
      if (isNaN(year) || (year < 2011) || (year > 3000))
        return '';

      if (isNaN(week) || (week <= 0) || (week > 60))
        return '';

      var fdoy = new Date(year, 0, 1);
      var fdow=fdoy.getDay();
      
      var aPs = [1, 0, 6, 5, 4, 3, 2];
      var P = aPs[fdow];
      
      var S = 1000 * 60 * 60 * 24;
      
      if (week < 1)
        week = 1;
      
      var start = fdoy.getTime() + ((week - 1) * 7 + P) * S;
      
      var dStart = new Date(start);
      var dStop  = new Date(start + S * 6);
      
      return dStart.getDate() + '.' + (dStart.getMonth() + 1) + '.' + dStart.getFullYear() + ' - ' + 
              dStop.getDate() + '.' +  (dStop.getMonth() + 1) + '.' +  dStop.getFullYear();
    }

    bEdit = false;

    function check()
    {
      var status = '';

      var year = parseInt(document.getElementById('year').value);

      if (isNaN(year) || (year < 2011))
        status = 'Некорректно задан год';
      else
      {
        document.getElementById('period').innerHTML = getWeekPeriod();

        if (period == '')
          status = 'Некорректно задан номер недели';
        else
        {
          var drv = parseInt(document.getElementById('fld_form').elements['driver'].value);
          var pas = parseInt(document.getElementById('fld_form').elements['passenger'].value);
            
          if (drv == pas)
            status = 'Водитель и Пассажир должны отличаться';
          else 
          {
            if (isTrip() && (getDays() == 0))
              status = 'Не отмечены дни недели';
            else
            {
              var prc = parseInt(document.getElementById('fld_form').elements['price'].value);

              if (isNaN(prc) || (prc == 0))
              {
                if (isTrip())
                  status = 'Не задана цена';
                else
                  status = 'Не задана сумма';
              }
            }
          }
        }
      }

      if (isTrip())
        document.getElementById('price_label').innerHTML = 'Цена';
      else
        document.getElementById('price_label').innerHTML = 'Сумма';
      
      document.getElementById('status').innerHTML = status;

      var x = document.getElementById('button');
      if (status != '')
      {
        if (!bEdit)
          x.innerHTML = '';
        else
          x.innerHTML = '<input type="submit" class="LiteButton" id="delete" value="Удалить"   onClick="myClick(3)" />' +
                        '<input type="submit" class="LiteButton" id="common" value="Отменить"  onClick="myClick(4)" />';
      }
      else
      {
        if (!bEdit)
          x.innerHTML = '<input type="submit" class="LiteButton" id="update" value="Добавить"  onClick="myClick(1)" />';
        else
          x.innerHTML = '<input type="submit" class="LiteButton" id="update" value="Сохранить" onClick="myClick(2)" />' +
                        '<input type="submit" class="LiteButton" id="delete" value="Удалить"   onClick="myClick(3)" />' +
                        '<input type="submit" class="LiteButton" id="common" value="Отменить"  onClick="myClick(4)" />';
      }
    }

    function checkOper(_oper,_days)
    {
      makeWeek(_oper,_days);
      check();
    }
    
    firstDraw = true;

    function doFirstDraw(_oper,_days)
    {
      if (firstDraw)
      {
        firstDraw = false;
        checkOper(_oper,_days);
      }
    }

    function addCommas(input) 
    {
      output = input.toString();
      var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
      while(sRegExp.test(output)) 
      {
        output = output.replace(sRegExp, '$1 $2');
      }
      document.write(output);
    }

  </script>
  
  <div id="gmenu" class="menu"> <a href="/">             {{ app_text  }}  </a> |
                                <a href="/trip?count=1"> {{ count_text }} </a> | 
                                <a href="/trip/person">  {{ pers_text }}  </a> </div>
  
  <div class="PageTitle">   {{page_title}}   </div>
  <div class="PageSummary"> {{trip_summary}} </div>
  <div class="PageStatus">  {{trip_status}}  </div>

  <form id="fld_form" action="/trip" method="post">
    <input name="pid"    type="hidden" value="{{ cur.pid }}">
    <input name="action" type="hidden" value="none">
    <input name="ret_days" type="hidden" value="0">
    <table class="fl1"><tbody>
      {% if edit_rec %} 
      <script language="javascript" type="text/javascript"> bEdit = true; </script>
      <tr><td class="fl1"> ID:     </td><td class="fl2"> {{ cur.pid }} </td> </tr>
      {% else %}
      <script language="javascript" type="text/javascript"> bEdit = false; </script>
      {% endif %} 
      <tr><td class="fl1"> Год:    </td><td class="fl2"> <input id="year" name="year" type="number" value="{{ cur.year }}" onChange="check()" /> </td> </tr>
      <tr><td class="fl1"> Неделя: </td><td class="fl2"> <input id="week" name="week" type="number" value="{{ cur.week }}" onChange="check()" /> </td>
                                        <td><span id="period"></span></td></tr>
      <tr><td class="fl1"> Операция </td>
          <td class="fl2">
            <script language="javascript" type="text/javascript">setRadio(0,{{cur.oper}},"{{oper_trip}}")</script>
            <script language="javascript" type="text/javascript">setRadio(1,{{cur.oper}},"{{oper_pay}}") </script>
          </td> </tr>
      <tr><td class="fl1"> Водитель </td>
          <td class="fl2">
            <select name="driver" onChange="check()" >
              {% for p in persons %}
                <script language="javascript" type="text/javascript">
                  setOption({{p.pid}},{{cur.driver}})</script> 
                  {{ p.name }}</option>
              {% endfor %}
            </select>
          </td></tr>
      <tr><td class="fl1"> Пассажир </td>
          <td class="fl2">
            <select name="passenger" onChange="check()" >
              {% for z in persons %}
                <script language="javascript" type="text/javascript">
                  setOption({{z.pid}},{{cur.passenger}})</script> 
                  {{ z.name }}</option>
              {% endfor %}
            </select>
          </td></tr>
      <tr id="days_row"> </tr>
      <script language="javascript" type="text/javascript">doFirstDraw({{cur.oper}},{{cur.days}})</script>
      <tr><td class="fl1"><span id="price_label"></span></td><td class="fl2"> <input name="price" size="15" type="number" value="{{ cur.price }}" onChange="check()" /> </td> </tr>
      <tr><td class="fl1"> Описание </td><td class="fl2"> <input name="text"  size="15" type="text"   value="{{ cur.text }}" /> </td> </tr>
    </tbody></table>

    <span id="button"> </span> 
    <span id="status" class="PageStatus"> </span> 
    <script language="javascript" type="text/javascript"> check() </script>
  </form>

  {% if trips.count %}
  <table class="work">
    <tbody><tr>
      <th class="work"> ID      </th>
      <th class="work"> Год     </td>
      <th class="work"> Н       </td>
      <th class="work"> Опер.   </td>
      <th class="work"> Дни     </td>
      <th class="work"> Вод.    </td>
      <th class="work"> Пасс.   </td>
      <th class="work"> Цена    </td>
      <th class="work"> Сумма   </td>
      <th class="work"> Коммент </td>
    </tr>
    {% for t in trips %}
    <tr class={{ t.c_oper }}>
      <td class="pid">  <script language="javascript" type="text/javascript">getLink({{ t.pid }})</script> </td>
      <td class="work"> {{ t.year }}   </td>
      <td class="work"> {{ t.week }}   </td>
      <td class="work"> {{ t.s_oper }} </td>
      <td class="work"> {{ t.s_days }} </td>
      <td class="work"> {{ t.s_driv }} </td>
      <td class="work"> {{ t.s_pass }} </td>
      <td class="numb"> <script language="javascript" type="text/javascript">addCommas({{ t.s_prc }})</script> </td>
      <td class="numb"> <script language="javascript" type="text/javascript">addCommas({{ t.summa }})</script> </td>
      <td class="work"> {{ t.text }}   </td>
    </tr>
    {% endfor %}
  </tbody></table>
  {% endif %}

  <br/>Всего операций: {{ trips.count }}<br/>

{% endblock %}
